import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { getStorage, setStorage } from '@/stores/storage'

export const useCognitionStore = defineStore('cognition', () => {
  // ==================== 状态定义 ====================
  const categories = ref(['想法', '人际']) // 固定分类在前
  const activeCategory = ref('想法') // 当前选中分类
  const contents = ref({
    // 数据结构
    '想法': [], // {id, title, content, mindMapData, isPinned, createdAt, updatedAt}
    '人际': []  // {id, name, relation, birthday, features, isPinned, createdAt, updatedAt}
  })

  // ==================== 数据初始化 ====================
  const initFromStorage = async () => {
    const saved = await getStorage('cognitionData')
    if (saved) {
      // 合并默认分类和自定义分类
      categories.value = ['想法', '人际', ...(saved.categories?.filter(c => !['想法', '人际'].includes(c)) || [])]
      activeCategory.value = saved.activeCategory || '想法'
      contents.value = {
        '想法': saved.contents?.['想法'] || [],
        '人际': saved.contents?.['人际'] || [],
        ...(saved.contents || {})
      }
    }
  }

  // ==================== 计算属性 ====================
  const currentContents = computed(() => {
    const items = contents.value[activeCategory.value] || []
    // 置顶项优先，按更新时间倒序
    return [...items].sort((a, b) => {
      if (a.isPinned !== b.isPinned) return a.isPinned ? -1 : 1
      return new Date(b.updatedAt) - new Date(a.updatedAt)
    })
  })

  // ==================== 分类操作 ====================
  const addCategory = async (name) => {
    if (!name || categories.value.includes(name)) return false
    
    categories.value.push(name)
    contents.value[name] = []
    await saveToStorage()
    return true
  }

  const deleteCategory = async (name) => {
    if (['想法', '人际'].includes(name)) return false
    
    const index = categories.value.indexOf(name)
    if (index === -1) return false

    categories.value.splice(index, 1)
    delete contents.value[name]

    // 切回默认分类
    if (activeCategory.value === name) {
      activeCategory.value = '想法'
    }

    await saveToStorage()
    return true
  }

  const switchCategory = async (name) => {
    if (categories.value.includes(name)) {
      activeCategory.value = name
      await saveToStorage()
      return true
    }
    return false
  }

  // ==================== 内容操作 ====================
  const addContent = async (contentData) => {
    if (!activeCategory.value) return null

    const now = new Date().toISOString()
    const newContent = {
      ...contentData,
      id: Date.now().toString(),
      isPinned: false,
      createdAt: now,
      updatedAt: now
    }

    if (!contents.value[activeCategory.value]) {
      contents.value[activeCategory.value] = []
    }

    contents.value[activeCategory.value].unshift(newContent)
    await saveToStorage()
    return newContent.id
  }

  const updateContent = async (contentId, updates) => {
    const categoryContents = contents.value[activeCategory.value]
    const index = categoryContents.findIndex(c => c.id === contentId)
    
    if (index !== -1) {
      const updatedAt = new Date().toISOString()
      categoryContents[index] = { 
        ...categoryContents[index], 
        ...updates,
        updatedAt 
      }
      await saveToStorage()
      return true
    }
    return false
  }

  const deleteContent = async (contentId) => {
    const categoryContents = contents.value[activeCategory.value]
    const index = categoryContents.findIndex(c => c.id === contentId)
    
    if (index !== -1) {
      categoryContents.splice(index, 1)
      await saveToStorage()
      return true
    }
    return false
  }

  const togglePinContent = async (contentId) => {
    const categoryContents = contents.value[activeCategory.value]
    const index = categoryContents.findIndex(c => c.id === contentId)
    
    if (index !== -1) {
      categoryContents[index].isPinned = !categoryContents[index].isPinned
      categoryContents[index].updatedAt = new Date().toISOString()
      await saveToStorage()
      return true
    }
    return false
  }

  // ==================== 特殊分类方法 ====================
  // 想法相关操作
  const updateMindMap = async (contentId, mindMapData) => {
    if (activeCategory.value !== '想法') return false
    return updateContent(contentId, { mindMapData })
  }

  // 人际相关操作
  const addContactFeature = async (contactId, featureText) => {
    if (activeCategory.value !== '人际') return false
    
    const categoryContents = contents.value[activeCategory.value]
    const index = categoryContents.findIndex(c => c.id === contactId)
    
    if (index !== -1) {
      if (!categoryContents[index].features) {
        categoryContents[index].features = []
      }
      
      const newFeature = {
        id: Date.now().toString(),
        text: featureText,
        completed: false,
        createdAt: new Date().toISOString()
      }
      
      categoryContents[index].features.push(newFeature)
      categoryContents[index].updatedAt = new Date().toISOString()
      await saveToStorage()
      return newFeature.id
    }
    return false
  }

  // ==================== 持久化方法 ====================
  const saveToStorage = async () => {
    return setStorage('cognitionData', {
      categories: categories.value.filter(c => !['想法', '人际'].includes(c)),
      activeCategory: activeCategory.value,
      contents: contents.value
    })
  }

  // ==================== 导出 ====================
  return {
    // 状态
    categories,
    activeCategory,
    contents,
    
    // 计算属性
    currentContents,
    
    // 方法
    initFromStorage,
    addCategory,
    deleteCategory,
    switchCategory,
    addContent,
    updateContent,
    deleteContent,
    togglePinContent,
    updateMindMap,
    addContactFeature,
    saveToStorage
  }
})